package com.bianmaba.example.eacache;

/**
 * @program: example-web-framework-extends
 * @description:
 * @author: Chenjiabin
 * @create: 2018-04-21 18:15
 **/

import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.Status;
import net.sf.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by yangjinfeng on 2017/1/5.
 */
public class DefaultCacheEventListener implements CacheEventListener {

    private Logger logger = LoggerFactory.getLogger(getClass());
    protected Status status;
    private boolean enabled;

    public DefaultCacheEventListener(boolean enabled) {
        this.enabled = enabled;
    }

    @Override
    public void notifyElementRemoved(Ehcache ehcache, Element element) throws CacheException {
        if (enabled) {
            logger.info("数据从二级缓存移除：键 = {}, 值 = {}, 缓存名称 = {}", element.getObjectKey(), element.getObjectValue(), ehcache.getName());
        }
    }

    @Override
    public void notifyElementPut(Ehcache ehcache, Element element) throws CacheException {
        if (enabled) {
            logger.info("数据推入二级缓存：键 = {}, 值 = {}, 缓存名称 = {}", element.getObjectKey(), element.getObjectValue(), ehcache.getName());
        }
    }

    @Override
    public void notifyElementUpdated(Ehcache ehcache, Element element) throws CacheException {
        if (enabled) {
            logger.info("数据刷新：键 = {}, 值 = {}, 缓存名称 = {}", element.getObjectKey(), element.getObjectValue(), ehcache.getName());
        }
    }

    @Override
    public void notifyElementExpired(Ehcache ehcache, Element element) {
        if (enabled) {
            logger.info("数据过期：键 = {}, 值 = {}, 缓存名称 = {}", element.getObjectKey(), element.getObjectValue(), ehcache.getName());
        }
    }

    @Override
    public void notifyElementEvicted(Ehcache ehcache, Element element) {
        if (enabled) {
            logger.info("数据删除：键 = {}, 值 = {}", element.getObjectKey(), element.getObjectValue(), ehcache.getName());
        }
    }

    @Override
    public void notifyRemoveAll(Ehcache ehcache) {
        if (enabled) {
            logger.info("清空缓存：缓存名 = {}", ehcache.getName());
        }
    }


    public final void dispose() {
        this.status = Status.STATUS_SHUTDOWN;
    }

    public Object clone() throws CloneNotSupportedException {
        super.clone();
        return new DefaultCacheEventListener(enabled);
    }
}